﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.IO;
using System.Windows.Forms;

namespace ConsoleStudy
{
    public class FlyPC
    {
        /// <summary>
        /// 获取cpu序列号
        /// </summary>
        /// <returns></returns>
        public static string CpuId()
        {                    
            try 
            { 
                string cpuInfo = "";//cpu序列号 
                ManagementClass mc = new ManagementClass("Win32_Processor"); 
                ManagementObjectCollection moc = mc.GetInstances(); 
                foreach (ManagementObject mo in moc) 
                { 
                    cpuInfo = mo.Properties["ProcessorId"].Value.ToString(); 
                } 
                moc = null; 
                mc = null; 
                return cpuInfo; 
            } 
            catch 
            { 
                return "unknown"; 
            }          
        }

        /// <summary>
        /// 获取MAC地址
        /// </summary>
        /// <returns></returns>
        public static string Mac()
        {
            const int MIN_MAC_ADDR_LENGTH = 12;
            string macAddress = string.Empty;
            long maxSpeed = -1;
            try
            {
                foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
                {
                    string tempMac = nic.GetPhysicalAddress().ToString();
                    if (nic.Speed > maxSpeed && !string.IsNullOrEmpty(tempMac) && tempMac.Length >= MIN_MAC_ADDR_LENGTH)
                    {
                        maxSpeed = nic.Speed;
                        macAddress = tempMac;
                    }
                }
                return macAddress;
            }
            catch
            {
                return "unknown";
            }
        }

        /// <summary>
        /// 获取硬盘序列号
        /// </summary>
        /// <returns></returns>
        public static string HardDiskId()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                String strHardDiskID = null;
                foreach (ManagementObject mo in searcher.Get())
                {
                    strHardDiskID = mo["SerialNumber"].ToString().Trim();
                    break;
                }
                return strHardDiskID;
            }
            catch
            {
                return "unknown";
            }
        }

        /// <summary>
        /// 获取内存条序列号
        /// </summary>
        /// <returns></returns>
        public static string MemoryId()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["TotalPhysicalMemory"].ToString();
                    break;
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknown";
            }
        }

        /// <summary>
        /// 生成机器码(mac地址+硬盘序列号+内存序列号)
        /// </summary>
        /// <returns></returns>
        public static string GenerateMacCode()
        {
            string mac = Mac() + HardDiskId() + MemoryId();
            return mac;
        }

        /// <summary>
        /// 生成激活文件
        /// </summary>
        public static void GenerateActiveFile()
        {
            string mac = GenerateMacCode();
            string code = Md5(mac);
            string licencePath = Path.Combine(Application.StartupPath, "licence.fly");
            if (File.Exists(licencePath))
            {
                File.Delete(licencePath);
            }
            FileStream fs = new FileStream(licencePath, FileMode.Create);
            //获得字节数组
            byte[] data = System.Text.Encoding.Unicode.GetBytes(code);
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();       
        }

        /// <summary>
        /// 验证激活密钥是否正确
        /// </summary>
        /// <param name="secretKey"></param>
        /// <returns></returns>
        public static bool CheckSecretKey(string secretKey)
        {
            bool result = false;
            string mac = GenerateMacCode();
            if (secretKey == Md5(mac))
            {
                GenerateActiveFile();
                result = true;               
            }
            return result;
        }

        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Md5(string str)
        {
            string cl = str;
            string pwd = "";
            MD5 md5 = MD5.Create();//实例化一个md5对像
            // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 
                pwd = pwd + s[i].ToString("x2");
            }
            return pwd;
        }
    }
}
